import { useRef } from 'react';
import { useActorRef, useSelector } from '@xstate/react';

import { TodosContext } from '../contexts/todo';
import type { TodoItem } from '../machines/todosMachine';
import { todoMachine } from '../machines/todoMachine';


export function useTodoActions(todo: TodoItem) {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const todosActorRef = TodosContext.useActorRef();
  const todoActorRef = useActorRef(
    todoMachine.provide({
      actions: {
        onCommit: ({ context }) => {
          todosActorRef.send({
            type: 'todo.commit',
            todo: {
              ...todo,
              title: context.title
            }
          });
        },
        focusInput: () => {
          setTimeout(() => {
            if (inputRef.current) {
              inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
              inputRef.current.focus();
            }
          });
        }
      }
    }),
    {
      input: { todo }
    }
  );
  const { send } = todoActorRef;
  const title = useSelector(todoActorRef, (s) => s.context.title);
  const isEditing = useSelector(todoActorRef, (s) => s.matches('editing'));

  return { send, title, isEditing, inputRef };
}
